﻿﻿using DeviceCommons.DataHandling;

namespace DeviceCommons.DeviceMessages.Models.V1
{
    public class DeviceMessageInfoReadings : IDeviceMessageInfoReadings
    {
        public byte Count { get => (byte)(ReadingArray?.Length ?? 0); }
        public IDeviceMessageInfoReading[]? ReadingArray { get; set; }

        public int DataLength => 1 + (ReadingArray?.Sum(i => i.DataLength) ?? 0);

        public void Dispose()
        {
            if (ReadingArray != null && ReadingArray.Length > 0)
            {
                // 清理数组中每个reading的State（State实现了IDisposable）
                foreach (var reading in ReadingArray)
                {
                    reading?.State?.Dispose();
                }
                // 只清理数组内容，不返回到内存池
                // 因为ReadingArray通常不是从内存池租借的（通过new IDeviceMessageInfoReading[]创建）
                Array.Clear(ReadingArray, 0, ReadingArray.Length);
                ReadingArray = [];
            }
            GC.SuppressFinalize(this);
        }
    }
}
